package com.qys.livesMall.anchor.controller.app;


import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qys.livesMall.anchor.enums.AnchorApplyStatusEnum;
import com.qys.livesMall.anchor.model.dto.H2AnchorApplyDTO;
import com.qys.livesMall.anchor.model.dto.H2AnchorContractDTO;
import com.qys.livesMall.anchor.model.dto.H2AnchorEditDTO;
import com.qys.livesMall.anchor.model.entity.H2AnchorApply;
import com.qys.livesMall.anchor.model.vo.*;
import com.qys.livesMall.anchor.model.vo.lives.app.SettlementDataVO;
import com.qys.livesMall.anchor.service.AnchorStatisticsTaskService;
import com.qys.livesMall.anchor.service.H2AnchorApplyService;
import com.qys.livesMall.anchor.service.H2AnchorService;
import com.qys.livesMall.app.user.mapper.H2AppUserMapper;
import com.qys.livesMall.app.user.model.entity.AppUserConcern;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.model.entity.H2AppUserBalance;
import com.qys.livesMall.app.user.service.AppUserConcernService;
import com.qys.livesMall.app.user.service.IH2AppUserBalanceService;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.DateUtils;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.framework.view.BaseQuery;
import com.qys.livesMall.shop.mapper.H2ShopBaseMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 主播申请控制器
 *
 * @author yxh
 * @since 2023-06-16 09:46:14
 */
@RestController
@RequestMapping("/app/anchor")
@Tag(name = "App-主播申请", description = "App-主播申请")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AppAnchorApplyController {

    private final H2AnchorApplyService h2AnchorApplyService;
    private final H2AnchorService anchorService;
    private final AppUserConcernService userConcernService;
    private final H2ShopBaseMapper shopBaseMapper;
    private final H2AppUserMapper userMapper;
    private final AnchorStatisticsTaskService anchorStatisticsTaskService;
    private final IH2AppUserBalanceService appUserBalanceService;

    /**
     * 根据用户ID查询申请
     *
     * @return 结果
     */
    @GetMapping("/getApply")
    @Operation(summary = "根据用户ID查询申请")
    public R<H2AnchorApplyVO> getApply() {
        LambdaQueryWrapper<H2AnchorApply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(H2AnchorApply::getUserId, SecurityUtils.getUserId()).ne(H2AnchorApply::getStatus,AnchorApplyStatusEnum.FAIL.getCode());
        H2AnchorApply anchorApply = h2AnchorApplyService.getOne(queryWrapper);
        if(null == anchorApply){
            return R.ok();
        }

        H2AnchorApplyVO h2AnchorApplyVO = new H2AnchorApplyVO();
        BeanUtils.copyProperties(anchorApply, h2AnchorApplyVO);
        h2AnchorApplyVO.setId(String.valueOf(anchorApply.getId()));
        h2AnchorApplyVO.setStatus(AnchorApplyStatusEnum.getByCode(anchorApply.getStatus()));
        return R.ok(h2AnchorApplyVO);
    }


    /**
     * 提交申请
     *
     * @param dto 实体对象
     * @return 新增结果
     */
    @PostMapping("/submit")
    @Operation(summary = "主播提交申请")
    public R<?> submit(@RequestBody @Validated H2AnchorApplyDTO dto) {
        return h2AnchorApplyService.submit(dto);
    }

    /**
     * 提交申请
     *
     * @param dto 实体对象
     * @return 新增结果
     */
    @PostMapping("/edit")
    @Operation(summary = "主播个人信息编辑")
    public R<?> edit(@RequestBody H2AnchorEditDTO dto) {
        return R.ok(anchorService.edit(dto));
    }

    /**
     * 获取主播合同
     * @return
     */
    @GetMapping("/getContract")
    @Operation(summary = "获取主播合同")
    public R<AnchorContractVO> getContract() {
        return R.ok(h2AnchorApplyService.getContract());
    }

    /**
     * 签订合同
     * @return
     */
    @PostMapping("/conclude")
    @Operation(summary = "签订合同")
    public R conclude(@RequestBody H2AnchorContractDTO dto) {
        h2AnchorApplyService.conclude(dto);
        return R.ok();
    }

    /**
     * 查询主播列表（首页）
     */
    @PostMapping("/anchorList")
    @Operation(summary = "查询主播列表（首页）")
    public R<IPage<AppAnchorVO>> anchorList(@RequestBody BaseQuery dto){
        return R.ok(anchorService.anchorList(dto));
    }


    /**
     * 查询主播个人信息
     */
    @GetMapping("/anchorInfo/{userId}")
    @Operation(summary = "查询主播个人信息")
    public R<AppAnchorVO> anchorInfo(@PathVariable Long userId){
        AppAnchorVO appAnchorVO;
        try {
            appAnchorVO = anchorService.getAnchorInfo(userId);
            H2AppUserBalance userBalance = appUserBalanceService.queryByUserId(userId);
            appAnchorVO.setAnchorBalance(userBalance.getBalance().toString());

            Wrapper<AppUserConcern> wrapper = Wrappers.<AppUserConcern>lambdaQuery()
                    .eq(AppUserConcern::getConcernId, userId)
                    .eq(AppUserConcern::getStatus, 1);
            long count = userConcernService.count(wrapper);
            appAnchorVO.setFans((int) count);

            Long shopId = shopBaseMapper.queryShopBaseIdByUserId(userId);
            appAnchorVO.setShopId(shopId);

            H2AppUser appUser = userMapper.selectById(userId);
            appAnchorVO.setAnchorAvatar(appUser.getAvatar());

        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok(appAnchorVO);
    }

    /**
     * 查询主播个人信息
     */
    @GetMapping("/anchorInfo")
    @Operation(summary = "查询主播个人信息")
    public R<AppAnchorVO> anchorInfo(){
        AppAnchorVO appAnchorVO;
        try {
            Long userId=SecurityUtils.getUserId();
            appAnchorVO = anchorService.getAnchorInfo(userId);
            appAnchorVO.setAnchorBalance("200.0000");

            Wrapper<AppUserConcern> wrapper = Wrappers.<AppUserConcern>lambdaQuery()
                    .eq(AppUserConcern::getConcernId, userId)
                    .eq(AppUserConcern::getStatus, 1);
            long count = userConcernService.count(wrapper);
            appAnchorVO.setFans((int) count);

            Long shopId = shopBaseMapper.queryShopBaseIdByUserId(userId);
            appAnchorVO.setShopId(shopId);

            H2AppUser appUser = userMapper.selectById(userId);
            appAnchorVO.setAnchorAvatar(appUser.getAvatar());

        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
        return R.ok(appAnchorVO);
    }

    /**
     * 查询主播个人信息
     */
    @GetMapping("/comprehensiveData/{type}/{business}")
    @Operation(summary = "查询主播访客和销售数据", parameters = {@Parameter(name = "type", description = "1:周，2:月"),
                                                             @Parameter(name = "business", description = "ljxzfs：累计新增粉丝，ljcjdd：累计成交订单，ljcjrs：累计成交人数，cjzhl：成交转换率，dczgrs：单场最高人数，ljgkrs：累计观看人数，cjfszb：成交粉丝占比，fsfgl：粉丝复购率，rjgksc：人均观看时长")})
    public R<AnchorDataVO> anchorInfo(@PathVariable String type, @PathVariable String business){
        DateTime dateTime=null;
        if (type.equals("1")){
            dateTime=DateUtils.offsetDay(DateUtils.date(),-7);
        }else {
            dateTime=DateUtils.offsetDay(DateUtils.date(),-30);
        }
        Long userId=SecurityUtils.getUserId();
        List<String> list =anchorStatisticsTaskService.getAnchorStatisticsList(dateTime,business,userId);
        AnchorDataVO anchorDataVO= new AnchorDataVO();
        anchorDataVO.setDataList(list);
        return R.ok(anchorDataVO);
    }


    @PostMapping("/sendMail/{emailAddress}")
    @Operation(summary = "发送邮件")
    public R<?> sendMail(@PathVariable String emailAddress){
        anchorService.sendMail(emailAddress);
        return R.ok();
    }

    @GetMapping("/incomeInformation")
    @Operation(summary = "主播收益信息")
    public R<AnchorIncomeInformationVO> incomeInformation(){
        return R.ok(anchorService.incomeInformation(SecurityUtils.getUserId()));
    }

    @GetMapping("/salesMissionDetails/{anchorSellTaskId}")
    @Operation(summary = "带货任务结算详情")
    public R<SettlementDataVO> salesMissionDetails(@PathVariable Long anchorSellTaskId){
        return R.ok(anchorService.salesMissionDetails(SecurityUtils.getUserId(), anchorSellTaskId));
    }

}

